package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.zhihuishu.micro.course.dto.LessonDto;
import com.zhihuishu.micro.course.dto.LessonVideoDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.openapi.app.dto.LessonVideoWebDto;
import com.zhihuishu.micro.course.openapi.app.teacher.LessonVideoOpenService;
import com.zhihuishu.micro.course.service.ChapterService;
import com.zhihuishu.micro.course.service.LessonService;
import com.zhihuishu.micro.course.service.LessonVideoService;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

/**
 * 
 * @author 嵇鹏
 * @descption:小节接口
 * 
 * 
 */
@Service("lessonVideoOpenServiceForTeacherApp")
public class LessonVideoOpenServiceImpl implements LessonVideoOpenService {

    @Resource
    private LessonVideoService lessonVideoService;

    @Resource
    private LessonService lessonService;
    @Resource
    private ChapterService chapterService;
    
    Logger logger=LoggerFactory.getLogger(LessonVideoWebDto.class);
 

    @Override
    public RemoteResult<Integer> saveLessonVideo(LessonVideoWebDto lessonVideoWebDto, Long courseId,
            Long userId) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        try {
            Assert.notNull(lessonVideoWebDto, "lessonVideoWebDto不能为空");
            Assert.notNull(lessonVideoWebDto.getLessonId(), "lessonId不能为空");
            Assert.notNull(lessonVideoWebDto.getChapterId(), "chapterId不能为空");
            Assert.notNull(courseId, "courseId不能为空");
            Assert.notNull(userId, "userId不能为空");
            lessonVideoWebDto.setCourseId(courseId);
            lessonVideoWebDto.setId(null);
            LessonVideoDto lessonVideoDto = BeanHelper.transTo(lessonVideoWebDto, LessonVideoDto.class);
            lessonVideoDto.setLessonId(lessonVideoWebDto.getLessonId().longValue());
            Integer lessonVideoId=lessonVideoService.saveLessonVideo(lessonVideoDto);// 保存小节
            lessonVideoService.addLessonVideoOnCourseRedis(courseId, lessonVideoDto.getId());// 更新课程小节的关系缓存
            //lessonVideoService.touchLessonVideo(lessonVideoDto.getId());// 更新小节的Hash缓存
            int lessonVideoCount = lessonVideoService.getLessonChildrenCount(lessonVideoDto.getLessonId().intValue());// 查询节下面小节的数量
            LessonDto lessonDto = lessonService.get(lessonVideoWebDto.getLessonId().intValue());
            
            lessonService.updateLessonVideoInfoAndChildCount(lessonVideoWebDto.getLessonId().intValue(),
                    lessonVideoCount);// 更新掉节的相关视频信息 与子节的数量

            if (lessonDto.getHaveChildren() == 0) {// 判断节下面有没有小节,如果有 清除掉节视频在小节表中的数据
                lessonVideoService.deleteLessonVideoInfo(lessonVideoWebDto.getLessonId().intValue());// 删除节视频在CC_LESSON_VIDEO表中的数据
            }
            lessonService.touchLesson(lessonVideoWebDto.getLessonId().intValue());// 更新节缓存
            chapterService.touchChapter(lessonVideoDto.getChapterId().intValue());//更新章缓存
            
            // 添加日志
            LoggerTemplateUtil.saveLogger(String.format("为节%d添加小节,更新节的数据", lessonVideoWebDto.getLessonId()),
                    userId, LoggerCollectionEnum.lessonCollection, courseId);
            LoggerTemplateUtil.saveLogger(String.format("添加小节%d", lessonVideoDto.getId()), userId,
                   LoggerCollectionEnum.lessonVideoCollection, courseId);
            remoteResult.setResult(lessonVideoId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
            logger.error("app保存小节出错,参数信息为:{}",lessonVideoWebDto,e);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<LessonVideoWebDto> queryLessonVideoById(Integer lessonVideoId) {
        RemoteResult<LessonVideoWebDto> remoteResult = new RemoteResult<LessonVideoWebDto>();
        try {
            Assert.notNull(lessonVideoId, "lessonVideoId不能为空");
            LessonVideoDto lessonVideoDto = lessonVideoService.get(lessonVideoId);
            LessonVideoWebDto lessonVideoWebDto=BeanHelper.transTo(lessonVideoDto, LessonVideoWebDto.class);
            lessonVideoWebDto.setLessonId(lessonVideoDto.getLessonId().intValue());
            lessonVideoWebDto.setVideoSec(lessonVideoDto.getVideoSec()==null?0:lessonVideoDto.getVideoSec().intValue());
            remoteResult.setResult(lessonVideoWebDto);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<Void> updateLessonVideo(LessonVideoWebDto lessonVideoWebDto, Long courseId,
            Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(lessonVideoWebDto, "更新对象不能为空");
            Assert.notNull(lessonVideoWebDto.getId(), "id不能为null");
            LessonVideoDto lessonVideoDto = BeanHelper.transTo(lessonVideoWebDto, LessonVideoDto.class);
            lessonVideoService.updateLessonVideo(lessonVideoDto);// 更新小节
            lessonVideoService.touchLessonVideo(lessonVideoWebDto.getId());// 更新缓存
            LoggerTemplateUtil.saveLogger(String.format("更新小节%d", lessonVideoWebDto.getId()), userId,
                    LoggerCollectionEnum.lessonVideoCollection, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Void> deleteLessonVideo(Integer lessonVideoId, Long courseId, Long userId) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(lessonVideoId,"删除小节id不能为空");
            Assert.notNull(courseId,"courseId不能为null");
            Assert.notNull(userId,"userId不能为null");
            LessonVideoDto lessonVideoDto = lessonVideoService.get(lessonVideoId);
            lessonVideoService.deleteLessonVideo(lessonVideoId);//删除小节
            lessonVideoService.removeLessonVideoOnCourseRedis(courseId, lessonVideoId);//从小节--课程的章节缓存中移除该节
            if (lessonVideoDto.getLessonId()!=null) {
                Integer count=lessonVideoService.getLessonChildrenCount(lessonVideoDto.getLessonId().intValue());
                lessonService.updateChildCount(count,lessonVideoDto.getLessonId().intValue());//更新节中小节数量的字段
                lessonService.touchLesson(lessonVideoDto.getLessonId().intValue());//更新节缓存
            }
            lessonVideoService.updateMinusSortByLessonIdAndSort(lessonVideoDto.getLessonId(),lessonVideoDto.getRank());
            LoggerTemplateUtil.saveLogger(String.format("删除小节%d", lessonVideoId), userId, LoggerCollectionEnum.lessonVideoCollection, courseId);//记录日志
          
            
            
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;

    }

    @Override
    public RemoteResult<Void> updateLessonVideoSort(LessonVideoWebDto lessonVideoWebDto, Long courseId,
            Long userId) {
        RemoteResult<Void> remoteResult=new RemoteResult<Void>();
        try {
            Assert.notNull(lessonVideoWebDto,"更新对象不能为空");
            Assert.notNull(lessonVideoWebDto.getId(),"更新小节不能为空");
            Assert.notNull(lessonVideoWebDto.getOriginRank(),"原始位置不能为空");
            Assert.notNull(lessonVideoWebDto.getTargetRank(),"目标位置不能为空");
            LessonVideoDto lessonVideoDto = lessonVideoService.get(lessonVideoWebDto.getId());
            int orginPos=lessonVideoWebDto.getOriginRank();//初始位置
            int targetPos=lessonVideoWebDto.getTargetRank();//目标位置

            List<Integer> lessonVideoIds=null;//小节排序后影响到的其他小节顺序
            if (orginPos>targetPos) {//初始位置大于目标位置(4--->1)向前移动
                lessonVideoIds=lessonVideoService.queryPlusLessonVideoIdsContainSmall(targetPos,orginPos,lessonVideoDto.getLessonId());
                lessonVideoService.updatePlussLessonVideoSortContaninSmall(targetPos,orginPos,lessonVideoDto.getLessonId());
            }
            if (orginPos<targetPos) {//初始位置小于目标位置(1--->4)向后移动
                lessonVideoIds=lessonVideoService.queryMinusLessonVideoIdContainBig(orginPos,targetPos,lessonVideoDto.getLessonId());
                lessonVideoService.updateMinusLessonVideoSortContainBig(orginPos,targetPos,lessonVideoDto.getLessonId());
            }
            if (logger.isDebugEnabled()) {
                logger.debug("受到影响的其他小节为:{}",lessonVideoIds);
            }
            if (lessonVideoIds!=null&&lessonVideoIds.size()>0) {
                for (Integer tempLessonVideoId : lessonVideoIds) {
                    lessonVideoService.touchLessonVideo(tempLessonVideoId);//更新缓存
                }
            }
            lessonVideoService.updateLessonVideoSort(lessonVideoWebDto.getId(),targetPos);//更新小节顺序
            lessonVideoService.touchLessonVideo(lessonVideoWebDto.getId());//更新小节缓存
            LoggerTemplateUtil.saveLogger(String.format("更新节%d顺序,初始顺序%d,更新后顺序%d",lessonVideoWebDto.getId(),lessonVideoWebDto.getOriginRank(),lessonVideoWebDto.getTargetRank()),
                    userId, LoggerCollectionEnum.lessonVideoCollection, courseId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

}
